package thesis.filesharing.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.bo.StudentBO;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.web.viewmodel.RegisterViewModel;

public class RegisterValidator implements Validator {
	
	@Autowired
	private StudentBO studentBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return RegisterViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentId", "studentId.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentName", "studentName.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentEmail", "studentEmail.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "confirmPassword.required");
		
		RegisterViewModel model = (RegisterViewModel) target;
		
		if (model.getStudentId() != null && model.getStudentId().length() > 0) {
			Pattern studentIdPattern = Pattern.compile(Constants.STUDENT_ID_PATTERN);
			Matcher studentIdMatcher = studentIdPattern.matcher(model.getStudentId());
			if (!studentIdMatcher.matches()) {
				errors.rejectValue("studentId", "studentId.incorrectFormat");
			}
		}
		
		if (model.getStudentEmail() != null && model.getStudentEmail().length() > 0) {
			Pattern emailPattern = Pattern.compile(Constants.EMAIL_PATTERN);
			Matcher emailMatcher = emailPattern.matcher(model.getStudentEmail());
			if (!emailMatcher.matches()) {
				errors.rejectValue("studentEmail", "studentEmail.incorrectFormat");
			}
		}
		
		if ("NONE".equalsIgnoreCase(model.getClassName())) {
			errors.rejectValue("className", "className.required");
		}
		
		if ("NONE".equalsIgnoreCase(model.getCourse())) {
			errors.rejectValue("course", "course.required");
		}
		
		if (model.getPassword() != null && model.getPassword().length() > 0 &&
				model.getConfirmPassword() != null && model.getConfirmPassword().length() > 0 &&
				!model.getPassword().equals(model.getConfirmPassword())) {
			errors.reject("password.mismatch");
		}
		
		if (!errors.hasErrors()) {
			if (studentBO.findStudentById(model.getStudentId()) != null) {
				errors.reject("studentId.exists");
			}
			if (studentBO.findStudentByEmail(model.getStudentEmail()) != null) {
				errors.reject("studentEmail.exists");
			}
		}
	}
}
